import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { Toast } from 'vant';
Vue.use(VueRouter)
Vue.use(Toast);

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    children: [
      {
        path: 'popup',
        component: () => import('../components/popup/Popup.vue')
      }
    ],
    meta: {
      hasTabbar: true
    }
  },
  {
    path: '/channel/:id',
    component: () => import('../components/home/ChannelDetails.vue')
  },
  {
    path: '/brand/:id',
    component: () => import('../components/home/BrandDetails.vue')
  },
  {
    path: '/category',
    component: () => import('../views/Category.vue'),
    children: [
      {
        path: 'popup',
        component: () => import('../components/popup/Popup.vue')
      }
    ],
    meta: {
      hasTabbar: true
    }
  },
  {
    path: '/user',
    component: () => import('../views/User.vue'),
    meta: {
      hasTabbar: true
    }
  },
  {
    path: '/topic',
    component: () => import('../views/Topic.vue'),
    meta: {
      hasTabbar: true
    }
  },
  {
    path: '/cart',
    component: () => import('../views/Cart.vue'),
    meta: {
      hasTabbar: true
    }
  },
  {
    path: '/details/:id',
    component: () => import('../views/Details.vue')
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 全局的导航守卫 - 前置导航守卫 - 路由拦截
/* 
  如果是跳转到购物车页面，那么需要先判断是否登录（token）
  如果是跳转到其他任何页面，就直接next()
*/
router.beforeEach(function (to, from, next) {
  if (to.path === '/cart') {
    // 即将跳往购物车，先判断有没有token
    let token = localStorage.getItem('X-Nideshop-Token');
    if (token) {
      // 直接
      next();
    } else {
      // 显示一个即将跳转的toast
      Toast.loading({
        message: '请先登录...',
        forbidClick: true,
      });
      setTimeout(() => {
        // 没有token，跳去登录页
        next('/user');
      }, 2000)
    }
  } else {
    next();// 任何一个跳往的路由都必须有一个next()来帮他跳转
  }
})

export default router
